import { Injectable } from '@angular/core';
import { AddTableRequest } from '../models/form';
import { AuthService } from './auth.service';
import { HttpService } from './http.service';
import { AsyncData } from '../models/async-data';
import { LuckyDog, toLuckyDog, AbstractLuckyDog } from '../models/lucky-dog';
import { TableInfo } from '../models/user';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class LuckyTableService {
  cache = new Map<string, AbstractLuckyDog>();
  constructor(
    private http: HttpService,
    private authService: AuthService,
    private router: Router
  ) {}
  add(form: AddTableRequest, success: () => void) {
    if (!form.userId) {
      form.userId = this.authService.user.id;
    }
    this.http
      .post<AddTableRequest>('/luckytables', form)
      .subscribe(({ code, data, msg }: AsyncData<LuckyDog>) => {
        if (code === 1) {
          alert('添加成功');
          success();
          const luckyDog = toLuckyDog(data);
          this.cache.set(data.id, luckyDog);
          this.authService.user.tableInfoList.push(
            new TableInfo(luckyDog.id, luckyDog.title, luckyDog.count)
          );
        } else if (code === -1) {
          alert(msg);
        }
      });
  }
  get(id: string): AbstractLuckyDog {
    const result = this.cache.get(id);
    if (result !== undefined) {
      return result;
    } else {
      this.router.navigate(['/error']);
    }
  }
  checkTable(id: string): Observable<boolean> {
    return this.http.get<AbstractLuckyDog>('/luckytables/' + id).pipe(
      map(data => {
        if (data.code === 1) {
          this.cache.set(id, toLuckyDog(data.data));
          return true;
        }
        this.router.navigate(['/user']);
        return false;
      })
    );
  }
}
